package com.example.multinetty.netty.thirdprotocal;

//import com.cn.common.core.model.Response;
import com.alibaba.fastjson.JSONObject;
import com.example.multinetty.netty.thirdprotocal.vo.chat.ChatResponse;
import com.example.multinetty.netty.thirdprotocal.vo.chat.PrivateChatRequest;
import com.example.multinetty.netty.thirdprotocal.vo.chat.PublicChatRequest;
import com.example.multinetty.netty.thirdprotocal.vo.player.PlayerResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.nio.ByteOrder;
import java.nio.charset.Charset;

/**
 * <pre>
 * 数据包格式
 * +——----——+——-----——+——----——+——----——+——----——+——----——+
 * |  包头	|  模块号      |  命令号    |  结果码    |  长度       |   数据     |  
 * +——----——+——-----——+——----——+——----——+——----——+——----——+
 * </pre>
 * @author -琴兽-
 *
 */
public class ResponseEncoder extends MessageToByteEncoder<Response>{

	@Override
	protected void encode(ChannelHandlerContext ctx, Response response, ByteBuf buffer) throws Exception {
		
		System.out.println("返回请求:" + "module:" +response.getModule() +" cmd:" + response.getCmd() + " resultCode:" + response.getStateCode());
		
		//包头
		buffer.writeInt(ConstantValue.HEADER_FLAG);
		//module和cmd
		buffer.writeShort(response.getModule());
		buffer.writeShort(response.getCmd());
		//结果码
		buffer.writeInt(response.getStateCode());

		byte[] LENGTH_PLACEHOLDER = new byte[4];
		//获取当前的writeIndex的值
		int lengthPos = buffer.writerIndex();

		//长度
		int lenth = response.getData()==null? 0 : response.getData().length;
		if(lenth <= 0){
			buffer.writeInt(lenth);

		}else{
			buffer.writeBytes(LENGTH_PLACEHOLDER);
			//buffer.writeInt(lenth);
			//buffer.writeBytes(response.getData());
			//process(buffer,response);
			exprocess(buffer,response);

		}
		buffer.setInt(lengthPos, buffer.writerIndex() - lengthPos - 4);
		/*if(lenth <= 0){
			buffer.writeInt(lenth);
		}else{
			buffer.writeInt(lenth);
			buffer.writeBytes(response.getData());
		}*/
	}
	private void exprocess(ByteBuf buffer, Response response){
		ModuleCMDEnum moduleCMDEnum=ModuleCMDEnum.getByModuleandCmd(response.getModule(), response.getCmd());
		String urlfullpath="";
		if(moduleCMDEnum!=null){
			urlfullpath=moduleCMDEnum.fixUrlpath+moduleCMDEnum.independantpath;
		}
		String uri="";
		try {
			uri=new URI(urlfullpath).toASCIIString();//实际上需要从协议包中获取
		}catch (Exception ex){

		}
		UriComponents uriComponents = UriComponentsBuilder.fromUriString(uri).build();
		if(uriComponents.getPath().equalsIgnoreCase("/chatonline/registerAndLogin")
				||uriComponents.getPath().equalsIgnoreCase("/chatonline/login")){
			process(buffer,response);
		}
		if(uriComponents.getPath().equalsIgnoreCase("/chatonline/publicChat")){
			processpubliccontent(buffer,response);
		}
		if(uriComponents.getPath().equalsIgnoreCase("/chatonline/privateChat")){
			processprivatecontent(buffer,response);
		}
		if(uriComponents.getPath().equalsIgnoreCase("/chatonline/pushChat")){
			processpushcontent(buffer,response);
		}

	}
	private void processpubliccontent(ByteBuf buffer, Response response){
		ChatResponse chatResponse=JSONObject.parseObject(response.getData(),ChatResponse.class);
		Long valuelong=chatResponse.getSendPlayerId();
		buffer.writeLong(valuelong);

		String value=chatResponse.getSendPlayerName();
		byte data[] = value.getBytes(Charset.forName("UTF-8"));
		short len = (short) data.length;
		buffer.writeShort(len);
		buffer.writeBytes(data);

		String valueex=chatResponse.getTartgetPlayerName();
		byte dataex[] = valueex.getBytes(Charset.forName("UTF-8"));
		short lenex = (short) dataex.length;
		buffer.writeShort(lenex);
		buffer.writeBytes(dataex);

		buffer.writeByte(chatResponse.getChatType());

		//messgage
		String valuemessage=chatResponse.getTartgetPlayerName();
		byte datamessage[] = valuemessage.getBytes(Charset.forName("UTF-8"));
		short lenmessage = (short) dataex.length;
		buffer.writeShort(lenmessage);
		buffer.writeBytes(datamessage);
	}
	private void processprivatecontent(ByteBuf buffer, Response response){
		processpubliccontent(buffer,response);
	}
	private void processpushcontent(ByteBuf buffer, Response response){
		ChatResponse chatResponse=JSONObject.parseObject(response.getData(),ChatResponse.class);
		Long valuelong=chatResponse.getSendPlayerId();
		buffer.writeLong(valuelong);

		String value=chatResponse.getSendPlayerName();
		byte data[] = value.getBytes(Charset.forName("UTF-8"));
		short len = (short) data.length;
		buffer.writeShort(len);
		buffer.writeBytes(data);

		if(chatResponse.getTartgetPlayerName()==null){
			buffer.writeShort((short)0);
		}else {
			String valueex = chatResponse.getTartgetPlayerName();
			byte dataex[] = valueex.getBytes(Charset.forName("UTF-8"));
			short lenex = (short) dataex.length;
			buffer.writeShort(lenex);
			buffer.writeBytes(dataex);
		}
		buffer.writeByte(chatResponse.getChatType());

		//messgage
		String valuemessage=chatResponse.getMessage();
		byte datamessage[] = valuemessage.getBytes(Charset.forName("UTF-8"));
		short lenmessage = (short) datamessage.length;
		buffer.writeShort(lenmessage);
		buffer.writeBytes(datamessage);
		/*buffer.writeInt(response.getData().length);
		buffer.writeBytes(response.getData());*/
	}

	private void process(ByteBuf buffer, Response response) {

		PlayerResponse playerResponse=JSONObject.parseObject(response.getData(),PlayerResponse.class);
		/*ByteBufAllocator bufAllocator = PooledByteBufAllocator.DEFAULT;
		ByteOrder BYTE_ORDER = ByteOrder.BIG_ENDIAN;
		ByteBuf bufferX = bufAllocator.heapBuffer();
		bufferX = bufferX.order(BYTE_ORDER);*/

		Long valuelong=playerResponse.getPlayerId();
		buffer.writeLong(valuelong);

		String value=playerResponse.getPlayerName();
		byte data[] = value.getBytes(Charset.forName("UTF-8"));
		short len = (short) data.length;
		buffer.writeShort(len);
		buffer.writeBytes(data);

		buffer.writeInt(playerResponse.getLevel());
		buffer.writeInt(playerResponse.getExp());

	}
}
